//
//  HHSheetAlertControllerAnimated.m
//  InternetHospital
//
//  Created by chun.chen on 2022/4/21.
//  Copyright © 2022 HC. All rights reserved.
//

#import "HHSheetAlertControllerAnimated.h"
#import <Masonry/Masonry.h>

@implementation HHSheetAlertControllerAnimated

- (NSTimeInterval)transitionDuration:(id<UIViewControllerContextTransitioning>)transitionContext
{
    return 0.35;
}

- (void)animateTransition:(id<UIViewControllerContextTransitioning>)transitionContext
{
    UIViewController *fromVC = [transitionContext viewControllerForKey:UITransitionContextFromViewControllerKey];
    UIViewController *toVC = [transitionContext viewControllerForKey:UITransitionContextToViewControllerKey];
    if (!fromVC || !toVC) {
        return;
    }
    UIView *containerView = [transitionContext containerView];
    NSTimeInterval duration = [self transitionDuration:transitionContext];

    UIViewController *animateVC = nil;
    if ([toVC isKindOfClass:[UINavigationController class]]) {
        UINavigationController *navController = (UINavigationController *)toVC;
        animateVC = navController.topViewController;
    } else {
        animateVC = toVC;
    }

    if (toVC.isBeingPresented) {
        [containerView addSubview:animateVC.view];
        UIView *alertView = nil;
        if ([animateVC conformsToProtocol:@protocol(HHSheetAlertAnimatedController)]) {
            UIAlertController<HHSheetAlertAnimatedController> *alertVC = (UIAlertController<HHSheetAlertAnimatedController> *)animateVC;
            if (!alertView && [alertVC respondsToSelector:@selector(animateAlertView)]) {
                alertView = [alertVC animateAlertView];
            }
        } else {
            alertView = animateVC.view;
        }
        if (!alertView) {
            return;
        }

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:duration animations:^{
                [alertView mas_updateConstraints:^(MASConstraintMaker *make) {
                    make.bottom.mas_equalTo(0);
                }];
                [animateVC.view layoutIfNeeded];
            } completion:^(BOOL finished) {
                [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
            }];
        });
    } else if (fromVC.isBeingDismissed) {
        [UIView animateWithDuration:duration animations:^{
            fromVC.view.alpha = 0.0;
        } completion:^(BOOL finished) {
            [transitionContext completeTransition:![transitionContext transitionWasCancelled]];
        }];
    }
}

@end
